package com.syf.kit.core.dao.sql.parse;

import java.util.Map;

/**
 * 动态SQL转变为标准SQL，并返回SQL动态绑定参数列表（列表中参数顺序已经排列好）
 */
public class WildCharSQLParseUtil {
    static final String REPLACE_SQL_CONVERT_START_TOKEN = "${";
    static final String REPLACE_CONVERT_END_TOKEN = "}";
    static final String DYNAMIC_SQL_CONVERT_START_TOKEN = "#{";
    static final String DYNAMIC_SQL_CONVERT_END_TOKEN = "}";
    private GenericSqlConverter genericSqlConverter;

    private static ReplaceHolderConverter replaceHolderConverter = new ReplaceHolderConverter(REPLACE_SQL_CONVERT_START_TOKEN, REPLACE_CONVERT_END_TOKEN);

    public static WildCharSQLParseResult parseWildCharSQL(String dynamicSQL, Map<String, Object> paramMap) {
        if (dynamicSQL == null || "".equals(dynamicSQL)) {
            throw new NullPointerException("SQL是空字符串");
        }
        // 将替换占位符给处理掉
        dynamicSQL = replaceHolderConverter.parse(dynamicSQL, paramMap);
        // 将参数绑定占位符处理
        GenericSqlConverter genericSqlConverter = new GenericSqlConverter(DYNAMIC_SQL_CONVERT_START_TOKEN, DYNAMIC_SQL_CONVERT_END_TOKEN);
        String standardSQL = genericSqlConverter.parse(dynamicSQL,paramMap);

        return new WildCharSQLParseResult(standardSQL, genericSqlConverter.getParamNameList());
    }

}
